package com.jar.exercise.多线程.线程之间的通信;

/**
 * 继承Thread类
 * 使用notify(),notifyall(),wait()
 * 操作线程通信
 * 例子：消费者和生产者
 */
public class ThreadCommunication {
	public static void main(String[] args) {
		Product product = new Product();
		Consumer consumer = new Consumer(product);
		Producer producer = new Producer(product);
		producer.setName("生产者");
		consumer.setName("消费者");
		consumer.start();
		producer.start();
	}
}

class Product {
	/**
	 * 产品数量
	 */
	private int count;

	/**
	 * 生产产品
	 */
	public synchronized void produceProduct(String name) {
		if (count < 20) {
			count++;
			System.out.println(name + "：生产了第" + count + "个产品");
			notify();
		} else {
			try {
				wait();//等待
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 消费产品
	 */
	public synchronized void consumeProduct(String name) {
		if (count > 0) {
			System.out.println(name + "：消费了第" + count + "个产品");
			count--;
			notify();
		} else {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

/**
 * 生产者
 */
class Producer extends Thread {
	private Product product;

	public Producer(Product product) {
		this.product = product;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(10);
				product.produceProduct(getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}

		}
	}
}

/**
 * 消费者
 */
class Consumer extends Thread {
	private Product product;

	public Consumer(Product product) {
		this.product = product;
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(10);
				product.consumeProduct(getName());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
